// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require('gulp')
const browserSync = require('browser-sync')
const del = require('del')
const bs = browserSync.create()
const loadPlugins  = require('gulp-load-plugins')

// 清除文件
const clean = () => {
  return del(['dist', 'temp'])
}
const plugins = loadPlugins()


// 样式编译
const style = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass())
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 脚本编译
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

// 页面模板编译
const page = () => {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig())
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const image = () => {
  return src('src/assets/images/**', { base: 'src' })   
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
  return src('public/**', { base: 'puplic' })
    .pipe(dest('dist'))
}


const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  watch(['src/assets/images/**', 'src/assets/fonts/**', 'public/**'], bs.reload)

  bs.init({
    // 页面弹出提示
    notify: false,
    // 监听改变的目录
    files: 'dist/**',
    server: {
      baseDir: ['temp', 'src', 'public'],
    }
  })  
}

// 处理文件引用
const useref = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({ 
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))
}

const compile = parallel(style, script, page)

// 上线之前执行的任务
const build = series(
  clean, 
  parallel(
    series(compile, useref), image, font, extra
  )
)

// 开发阶段执行的任务
const develop = series(compile, serve)

module.exports = {
  build,
  develop,
  clean,
}